import sys
import requests
import os
import json
import time
import subprocess
from typing import Dict, List, Any, Optional
from pathlib import Path
from datetime import datetime
import pandas as pd

# 全局变量定义（集中管理配置和状态）
BASE_URL = "https://caigou.chinatelecom.com.cn"
TOKEN = ""
EXPORT_PATH = ""
DOWNLOAD_ROOT = ""
LOGGER = None
START_TIME = ""
END_TIME = ""
ORDER_CODE = ""
CONTRACT_CODE=""
PAGE_SIZE = 20  # 每页订单数量


class Logger:
    """日志工具类，同时输出到控制台和文件"""

    def __init__(self, log_file_path: str):
        log_dir = os.path.dirname(log_file_path)
        if not os.path.exists(log_dir):
            os.makedirs(log_dir, exist_ok=True)
        self.log_file = log_file_path

    def print(self, message: str) -> None:
        """打印并写入日志（带时间戳）"""
        print(message)
        with open(self.log_file, 'a', encoding='utf-8') as f:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            f.write(f"[{timestamp}] {message}\n")


def init_global_vars(args: Optional[List[str]] = None) -> None:
    """初始化所有全局变量（集中配置）"""
    global BASE_URL, TOKEN, EXPORT_PATH, DOWNLOAD_ROOT, LOGGER,START_TIME,END_TIME,ORDER_CODE,CONTRACT_CODE

    # 基础配置
    BASE_URL = "https://caigou.chinatelecom.com.cn"
    EXPORT_PATH = args[5]  # 导出根路径
    CONTRACT_CODE = args[1]  # 合同编号（单独提取便于维护）
    DOWNLOAD_ROOT = os.path.join(EXPORT_PATH, f"招投标合同发票证明材料")
    START_TIME = args[3]
    END_TIME = args[4]
    # 初始化日志
    log_file = os.path.join(EXPORT_PATH, "export_log.txt")
    LOGGER = Logger(log_file)
    token_data = json.loads(args[0])
    # 逐层检查键是否存在
    if "localStorage" not in token_data:
        LOGGER.print("token_data 中缺少 'localStorage' 字段")
        raise KeyError("token_data 中缺少 'localStorage' 字段")

    localStorage = token_data["localStorage"]
    if not isinstance(localStorage, dict):
        LOGGER.print("'localStorage' 不是字典类型")
        raise TypeError("'localStorage' 不是字典类型")

    if "Admin-Token" not in localStorage:
        LOGGER.print("'localStorage' 中缺少 'Admin-Token' 字段")
        raise KeyError("'localStorage' 中缺少 'Admin-Token' 字段")

    TOKEN = localStorage["Admin-Token"]
    # token = token_data["localStorage"]["Admin-Token"]

    LOGGER.print(f"导出路径: {EXPORT_PATH}")
    LOGGER.print(f"合同编号: {CONTRACT_CODE}")
    LOGGER.print(f"下载根目录: {DOWNLOAD_ROOT}")
    LOGGER.print(f"开始时间: {START_TIME}")
    LOGGER.print(f"结束时间: {END_TIME}")
    LOGGER.print(f"Token: {TOKEN}")

    # 初始化Token（实际使用时建议从安全渠道获取）
    #TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjBjN2Q1YWM1LWFjM2MtNDNiNS04Nzc5LWUxOTU5ZDE0ZWQ1YSJ9.N-7BzXFbQZWneVeBvAspz6k9up5qbjNn4GLgj3-wuuCO6skrmI6uWZH7sIejcfV0j9eMC9h3ow9LnEcq2xmm6g"

    # 初始化下载根目录
    try:
        os.makedirs(DOWNLOAD_ROOT, exist_ok=True)
        LOGGER.print(f"下载根目录: {os.path.abspath(DOWNLOAD_ROOT)}")
    except OSError as e:
        LOGGER.print(f"创建下载目录失败: {str(e)}")
        sys.exit(1)


def get_common_headers() -> Dict[str, str]:
    """获取通用请求头（避免重复定义）"""
    return {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,ru;q=0.8",
        "authorization": f"Bearer {TOKEN}",
        "content-type": "application/json;charset=UTF-8",
        "origin": "https://caigou.chinatelecom.com.cn",
        "referer": "https://caigou.chinatelecom.com.cn/statisticalSetting",
        "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
    }

#从sst下载采购订单
def download_to_sst(output_dir: str, output_file: str,order_code: str) -> None:
    """调用SSTTool处理文件（使用全局变量）"""
    # 构建工具路径（与脚本同目录）
    script_path = os.path.abspath(sys.argv[0])
    tool_path = os.path.join(os.path.dirname(script_path), "SSTTool.exe")
    output_path = os.path.join(output_dir, output_file)

    LOGGER.print(f"SSTTool处理路径: {output_path}")

    if not os.path.exists(tool_path):
        LOGGER.print(f"错误：SSTTool.exe不存在 - {tool_path}")
        return

    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)

    # 构建命令参数
    cmd_args = [
        tool_path,
        "-n", f"{output_file}-{order_code}",
        "-i", order_code,
        "-l", output_path
    ]

    # 隐藏命令行窗口
    startup_info = subprocess.STARTUPINFO()
    startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startup_info.wShowWindow = subprocess.SW_HIDE

    try:
        result = subprocess.run(
            cmd_args,
            startupinfo=startup_info,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=300
        )

        LOGGER.print("SSTTool执行成功")
        if result.stdout:
            LOGGER.print(f"SSTTool输出: {result.stdout[:200]}...")  # 限制输出长度

    except subprocess.CalledProcessError as e:
        LOGGER.print(f"SSTTool执行失败，返回码: {e.returncode}")
        LOGGER.print(f"错误输出: {e.stderr[:500]}...")
    except subprocess.TimeoutExpired:
        LOGGER.print("SSTTool执行超时（300秒）")
    except Exception as e:
        LOGGER.print(f"SSTTool调用异常: {str(e)}")

#根据框架合同号导出结算单列表
def export_telecom_bill():
    """
    导出电信采购平台账单数据为Excel

    Args:
        各参数同原函数描述

    Returns:
        保存文件的路径，失败则返回None
    """
    # 创建输出目录
    try:
        LOGGER.print(f"导出路径: {EXPORT_PATH}")
        os.makedirs(EXPORT_PATH, exist_ok=True)
    except OSError as e:
        LOGGER.print(f"创建Excel输出目录失败: {str(e)}")
        return None

    # 构建请求参数
    payload = {
        "pageNum": 1,
        "pageSize": 10,
        "createTimeStart": START_TIME,
        "createTimeEnd": END_TIME,
        "smallContractCode": CONTRACT_CODE
    }
    LOGGER.print(payload)
    try:
        # 发送请求
        response = requests.post(
            url="https://caigou.chinatelecom.com.cn/portal/provider/exportBill",
            headers=get_common_headers(),
            json=payload,
            stream=True,
            timeout=300
        )

        response.raise_for_status()

        # 解析文件名
        content_disposition = response.headers.get("content-disposition", "")
        if "filename=" in content_disposition:
            filename = content_disposition.split("filename=")[-1].strip('"')
        else:
            timestamp = time.strftime("%Y%m%d_%H%M%S")
            filename = f"bill_export_{timestamp}.xlsx"

        # 保存文件
        file_path = os.path.join(EXPORT_PATH, filename)
        with open(file_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)

        LOGGER.print(f"Excel文件已保存到: {file_path}")
        return file_path

    except requests.exceptions.RequestException as e:
        LOGGER.print(f"导出Excel请求异常: {str(e)}")
        return None
    except Exception as e:
        LOGGER.print(f"保存Excel文件失败: {str(e)}")
        return None

#下载竖版采购订单
def download_order_print(id: str, security_view_code: str, save_path: str, file_name: str) -> bool:
    """
    下载订单打印文件（竖版）

    Args:
        id: 订单ID
        security_view_code: 安全查看码
        save_path: 保存目录
        file_name: 保存的文件名（含扩展名）

    Returns:
        成功返回True，失败返回False
    """
    # 检查订单文件是否已存在
    full_save_path = os.path.join(save_path, file_name)
    if os.path.exists(full_save_path):
        file_size = os.path.getsize(full_save_path)
        if file_size >= 1024:  # 大于1KB认为有效
            LOGGER.print(f"订单文件已存在: {full_save_path}")
            return True
        else:
            LOGGER.print(f"发现不完整订单文件，将重新下载: {full_save_path}")
            os.remove(full_save_path)

    url = "https://caigou.chinatelecom.com.cn/portal/purchaseOrder/print"
    payload = {
        "id": id,
        "securityViewCode": security_view_code
    }

    try:
        Path(save_path).mkdir(parents=True, exist_ok=True)  # 确保目录存在

        with requests.post(
                url=url,
                headers=get_common_headers(),
                json=payload,
                stream=True,
                timeout=30
        ) as response:
            response.raise_for_status()

            # 写入文件
            total_bytes = 0
            with open(full_save_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        total_bytes += len(chunk)
                        f.write(chunk)

            # 验证文件有效性
            file_size = os.path.getsize(full_save_path)
            if file_size < 1024:  # 小于1KB可能异常
                LOGGER.print(f"警告: 订单文件{file_name}大小异常({file_size}字节)，可能不完整")

            LOGGER.print(f"订单文件已保存: {full_save_path}")
            return True

    except requests.exceptions.RequestException as e:
        LOGGER.print(f"订单下载请求失败: {str(e)}")
    except Exception as e:
        LOGGER.print(f"订单文件处理失败: {str(e)}")

    # 清理异常文件
    if os.path.exists(full_save_path):
        os.remove(full_save_path)
    return False

#下载结算单
def download_settlement_orders(
        id: str,
        security_view_code: str,
        security_delete_code: str,
        security_edit_code: str,
        save_path: str,
        file_name: str
) -> bool:
    """
    下载结算单文件（增加重复检查）

    Args:
        id: 结算单ID
        security_view_code: 安全查看码
        security_delete_code: 安全删除码
        security_edit_code: 安全编辑码
        save_path: 保存目录
        file_name: 保存的文件名（含扩展名）

    Returns:
        成功返回True，失败返回False
    """
    # 检查结算单文件是否已存在
    full_save_path = os.path.join(save_path, file_name)
    if os.path.exists(full_save_path):
        file_size = os.path.getsize(full_save_path)
        if file_size >= 1024:  # 大于1KB认为有效

            return True
        else:
            LOGGER.print(f"发现不完整结算单文件，将重新下载: {full_save_path}")
            os.remove(full_save_path)

    url = "https://caigou.chinatelecom.com.cn/portal/provider/jsdBatchPrint"
    payload = {
        "ids": id,
        "securityViewCode": security_view_code,
        "securityEditCode": security_edit_code,
        "securityDeleteCode": security_delete_code
    }

    try:
        Path(save_path).mkdir(parents=True, exist_ok=True)

        with requests.post(
                url=url,
                headers=get_common_headers(),
                json=payload,
                stream=True,
                timeout=30
        ) as response:
            response.raise_for_status()

            # 写入文件
            with open(full_save_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)

            # 验证文件有效性
            file_size = os.path.getsize(full_save_path)
            if file_size < 1024:
                LOGGER.print(f"警告: 结算单文件{file_name}大小异常({file_size}字节)，可能不完整")

            LOGGER.print(f"结算单文件已保存: {full_save_path}")
            return True

    except requests.exceptions.RequestException as e:
        LOGGER.print(f"结算单下载请求失败: {str(e)}")
    except Exception as e:
        LOGGER.print(f"结算单文件处理失败: {str(e)}")

    # 清理异常文件
    if os.path.exists(full_save_path):
        os.remove(full_save_path)
    return False

#查询竖版采购订单信息
def fetch_orders(order_code: str, base_save_path: str) -> str:
    """
    根据订单号获取订单信息并下载竖版订单文件
    目录结构：结算单目录 → 订单编号子目录 → 订单文件
    """
    url = "https://caigou.chinatelecom.com.cn/portal/purchaseOrder/listMyOrder"
    payload = {
        "pageNum": 1,
        "pageSize": 1,
        "orderCode": order_code,
        "subId": 2
    }

    try:
        response = requests.post(
            url=url,
            json=payload,
            headers=get_common_headers(),
            timeout=30
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") != 200:
            LOGGER.print(f"获取订单{order_code}信息失败: {result.get('msg')}")
            return base_save_path

        # 解析订单数据
        order_list = result.get("data", {}).get("pageInfo", {}).get("list", [])
        if not order_list:
            LOGGER.print(f"未找到订单{order_code}的详情数据")
            return base_save_path

        order_info = order_list[0]
        security_view_code = order_info.get("securityViewCode")
        order_id = order_info.get("id")
        order_code = order_info.get("orderCode", order_code)  # 确保订单编号不为空

        # 构建订单保存路径：结算单目录 + 订单编号子目录
        save_path = os.path.join(base_save_path, order_code)

        # 下载订单文件（存入订单编号子目录）
        download_order_print(
            id=order_id,
            security_view_code=security_view_code,
            save_path=save_path,
            file_name=f"{order_code}.pdf"
        )

        return save_path

    except requests.RequestException as e:
        LOGGER.print(f"订单{order_code}请求异常: {str(e)}")
    except Exception as e:
        LOGGER.print(f"处理订单{order_code}失败: {str(e)}")

    return base_save_path

#查询结算单信息
def fetch_settlement_orders(order_package_code: str,legal_order_code: str) -> str:
    """
    根据结算单号获取结算单信息并下载结算单文件
    目录结构：根目录 → 结算单编号目录 → 结算单文件
    """
    url = "https://caigou.chinatelecom.com.cn/portal/provider/listOrderPackage"
    payload = {
        "pageNum": 1,
        "pageSize": 1,
        "orderPackageCode": order_package_code,
    }

    try:
        response = requests.post(
            url=url,
            json=payload,
            headers=get_common_headers(),
            timeout=30
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") != 200:
            LOGGER.print(f"获取结算单{order_package_code}信息失败: {result.get('msg')}")
            return ""

        # 解析结算单数据
        settlement_list = result.get("data", {}).get("pageInfo", {}).get("list", [])
        if not settlement_list:
            LOGGER.print(f"未找到结算单{order_package_code}的详情数据")
            return ""

        settlement_info = settlement_list[0]
        # 提取必要参数
        security_view_code = settlement_info.get("securityViewCode")
        settlement_id = settlement_info.get("id")
        order_package_name = settlement_info.get("orderPackageName", order_package_code)
        security_delete_code = settlement_info.get("securityDeleteCode")
        security_edit_code = settlement_info.get("securityEditCode")
        order_package_code = settlement_info.get("orderPackageCode", order_package_code)
        save_dir = os.path.join(DOWNLOAD_ROOT, legal_order_code.split("-")[0])
        # 结算单保存目录：根目录/结算单号
        save_path = os.path.join(save_dir, order_package_code)
        # 下载结算单文件
        download_settlement_orders(
            id=settlement_id,
            security_view_code=security_view_code,
            security_delete_code=security_delete_code,
            security_edit_code=security_edit_code,
            save_path=save_path,
            file_name=f"{order_package_name}.pdf"
        )

        return save_path

    except requests.RequestException as e:
        LOGGER.print(f"结算单{order_package_code}请求异常: {str(e)}")
    except Exception as e:
        LOGGER.print(f"处理结算单{order_package_code}失败: {str(e)}")

    return ""


def query_goods_receipt_post(order_num):
    '''传入订单编号，查询收货列账'''
    try:
        url = 'https://caigou.chinatelecom.com.cn/portal/orderReport/list'
        payload = {
            "applyCompanyName": None,
            "applyTypeCode": None,
            "frameContName": None,
            "isProxyOrder": None,
            "managerName": None,
            "managerPhone": None,
            "modelCode": None,
            "modelName": None,
            "orderCode": order_num,  # 订单编号
            "originalName": None,
            "pageNum": 1,
            "pageSize": 10,
            "provinceCode": None,
            "purchaseApplyCompanyName": None,
            "receiveStatus": None,
            "sapCode": None,
            "serviceTypeCode": None,
            "smallContractCode": None,
            "stockOrderCode": None,
        }
        response = requests.post(url, json=payload, headers=get_common_headers())
        response.raise_for_status()
        result = response.json()

        if result.get('code') != 200:
            LOGGER.print(f"查询该订单收货列账信息失败: {result.get('msg')}")
            return []
        # 获取该订单的原厂商产品名称、原厂商规格型号、数量、设备单价（元）、设备费总价（元）、订单列账金额（元）
        data = result['data']['pageInfo']['list']
        if len(data) > 0:
            providerProductName = data[0]['providerProductName']  # 原厂商产品名称
            providerProductModel = data[0]['providerProductModel']  # 原厂商规格型号
            num = data[0]['num']  # 数量
            deviceSumPrice = data[0]['deviceSumPrice']  # 设备单价
            deviceSumAmount = data[0]['deviceSumAmount']  # 设备费总价
            totalInvoicedAmount = data[0]['totalInvoicedAmount']  # 订单列账金额
            return [providerProductName, providerProductModel, num, deviceSumPrice, deviceSumAmount,
                    totalInvoicedAmount]
        else:
            LOGGER.print(f"该订单未查询到收货列账信息: {result.get('msg')}")
            return []

    except requests.exceptions.RequestException as e:
        LOGGER.print(f"查询收货列账请求异常: {str(e)}")
    except Exception as e:
        LOGGER.print(f"查询收货列账失败: {str(e)}")


def query_my_order(order_num):
    '''传入订单编码，查询我的订单返回税款字段'''
    try:
        url = 'https://caigou.chinatelecom.com.cn/portal/purchaseOrder/listMyOrder'
        today = datetime.now().date().strftime('%Y-%m-%d')
        payload = {
            "applyTypeCodes": None,
            "collectState": "",
            "contractName": "",
            "createTimeEnd": "",
            "createTimeStart": today,  # 当天日期 2025-08-27
            "creatorName": "",
            "delivery": "",
            "frameContName": "",
            "isProxyOrder": "",
            "isSelfTake": "",
            "isSlhgl": "",
            "orderCode": order_num,
            "orderName": "",
            "orderOriginQuery": "",
            "pageNum": 1,
            "pageSize": 10,
            "providerDealStatus": "",
            "providerNameOfwl": "",
            "provinceCode": "",
            "purchaseApplyCompanyName": "",
            "purchaseTypeCode": "",
            "receiveStatus": "",
            "sapCode": "",
            "serviceTypeCode": "",
            "smallContractCode": "",
            "stockOrderCode": "",
            "subId": 2
        }
        response = requests.post(url, json=payload, headers=get_common_headers())
        response.raise_for_status()
        result = response.json()

        if result.get('code') != 200:
            LOGGER.print(f"查询我的订单信息失败: {result.get('msg')}")
            return None
        data = result['data']['pageInfo']['list']
        if len(data) > 0:
            taxAmount = data[0]['taxAmount']  # 税款
            return taxAmount
        else:
            LOGGER.print(f"该订单未查询到我的订单信息: {result.get('msg')}")
            return None


    except requests.exceptions.RequestException as e:
        LOGGER.print(f"查询我的订单请求异常: {str(e)}")
    except Exception as e:
        LOGGER.print(f"查询我的订单失败: {str(e)}")

def supple_settlement_statement(excel_path):
    '''
    在结算单导出的excel中增加市场（招投标）需求的字段
    用订单号调 查询收获列账的接口 返回原厂商产品名称、原厂商规格型号、数量、设备单价、设备费总价、订单列账金额
    再用订单号调 查询我的订单的接口 返回税款
    '''
    try:
        df = pd.read_excel(excel_path)
        required_columns = ['订单编码']
        for col in required_columns:
            if col not in df.columns:
                LOGGER.print(f"错误：结算单Excel缺少必要字段 - {col}")
                return None
        # 定义要添加的新列
        new_columns = [
            '原厂商产品名称',
            '原厂商规格型号',
            '数量',
            '设备单价（元）',
            '设备费总价（元）',
            '订单列账金额（元）',
            '税款'
        ]
        # 初始化新列
        for col in new_columns:
            df[col] = None
        for index,row in df.iterrows():
            order_num = row['订单编码']
            if pd.isna(order_num):
                continue
            # 用订单编号查询收获列账 和 我的订单
            goods_receipt_info = query_goods_receipt_post(order_num)
            taxAmount = query_my_order(order_num)
            if len(goods_receipt_info) > 0 and taxAmount:
                # excel增加字段
                df.at[index,'原厂商产品名称'] = goods_receipt_info[0]
                df.at[index,'原厂商规格型号'] = goods_receipt_info[1]
                df.at[index,'数量'] = goods_receipt_info[2]
                df.at[index, '设备单价（元）'] = goods_receipt_info[3]
                df.at[index, '设备费总价（元）'] = goods_receipt_info[4]
                df.at[index, '订单列账金额（元）'] = goods_receipt_info[5]
                df.at[index,'税款'] = taxAmount

            # 添加延迟避免请求过于频繁
            time.sleep(0.2)
        df.to_excel(excel_path, index=False)
        LOGGER.print(f"收货列账和我的订单字段补充完成，已保存到 {excel_path}")

    except Exception as e:
        LOGGER.print(f"在Excel文件中增加字段失败: {str(e)}")
        return None

#根据条件导出结算单excel
def process_excel_data(excel_path: str) -> None:
    """处理Excel文件，提取结算单和订单信息并下载对应文件"""
    if not os.path.exists(excel_path):
        LOGGER.print(f"错误：Excel文件不存在 - {excel_path}")
        return

    try:
        # 读取Excel数据
        df = pd.read_excel(excel_path, sheet_name=0)
        required_columns = ["结算单编号", "订单编码", "法律订单编码", "结算金额"]

        # 验证表头
        for col in required_columns:
            if col not in df.columns:
                LOGGER.print(f"错误：Excel缺少必要字段 - {col}")
                return

        # 处理每行数据
        total_rows = len(df)
        skipped_count = 0

        for index, row in df.iterrows():
            row_num = index + 2  # Excel行号（含表头）
            settlement_amount = row["结算金额"]

            # 跳过无效金额
            if pd.isna(settlement_amount) or settlement_amount == 0:
                skipped_count += 1
                LOGGER.print(f"跳过行{row_num}：结算金额为0或空")
                continue

            # 提取关键信息
            settlement_no = str(row["结算单编号"]).strip() if not pd.isna(row["结算单编号"]) else ""
            order_code = str(row["订单编码"]).strip() if not pd.isna(row["订单编码"]) else ""
            legal_order_code = str(row["法律订单编码"]).strip() if not pd.isna(row["法律订单编码"]) else ""

            # 验证结算单号
            if not settlement_no:
                LOGGER.print(f"跳过行{row_num}：结算单编号为空")
                skipped_count += 1
                continue

            LOGGER.print(f"\n处理行{row_num}/{total_rows}：结算单号={settlement_no}, 订单号={order_code}")

            # 下载结算单（获取保存目录）
            settlement_path = fetch_settlement_orders(settlement_no,legal_order_code)
            if not settlement_path:
                LOGGER.print(f"行{row_num}：结算单下载失败，跳过后续操作")
                continue

            # 下载订单文件（使用结算单目录作为基础目录）
            if order_code:
                fetch_orders(order_code, settlement_path)
            else:
                LOGGER.print(f"行{row_num}：订单编码为空，跳过订单下载")

            # 下载横版订单（按需启用）
            if legal_order_code:
                download_to_sst(settlement_path, order_code,legal_order_code)

        # 输出统计结果
        LOGGER.print(f"\n处理完成：共{total_rows}行，有效{total_rows - skipped_count}行，跳过{skipped_count}行")

    except Exception as e:
        LOGGER.print(f"Excel处理失败：{str(e)}")


def main():
    # 获取命令行参数
    args = sys.argv[1:]
    if len(args) < 7:
        LOGGER.print(
            "参数错误！使用方式: python script.py [token] [框架合同编号] [商品名称] [开始时间] [结束时间] [导出路径] [目录结构标识]")
        sys.exit(1)
    """主函数：初始化并执行流程"""
    init_global_vars(args)

    # 导出Excel并处理
    LOGGER.print("开始导出Excel数据...")
    excel_path = export_telecom_bill()
    if excel_path:
        LOGGER.print("开始处理Excel数据并下载文件...")
        supple_settlement_statement(excel_path)
        process_excel_data(excel_path)
    else:
        LOGGER.print("Excel导出失败，终止流程")


if __name__ == "__main__":
    main()